<template>
  <transition name="down" @after-leave="destroy">
    <div
      v-if="isVisable"
      class="min-w-[420px] fixed top-[40px] left-[50%] translate-x-[-50%] z-50 flex items-center px-3 py-2 rounded border cursor-pointer"
      :class="styles[type].containerClass"
    >
      <m-svg-icon :name="styles[type].icon" :fillClass="styles[type].fillClass" class="h-1.5 w-1.5 mr-1.5"></m-svg-icon>
      <span class="text-sm" :class="styles[type].textClass">{{content}}</span>
    </div>
  </transition>
</template>

<script>
const SUCCESS = 'success'
const WARN = 'warn'
const ERROR = 'error'
const typeEnum = [SUCCESS, WARN, ERROR]
</script>

<script setup>
import { onMounted, ref } from 'vue'
import mSvgIcon from '../svg-icon/index.vue'
const props = defineProps({
  // message 的消息类型
  type: {
    type: String,
    required: true,
    validator(val) {
      const result = typeEnum.includes(val)
      if (!result) {
        throw new Error(`你的 type 必须是 ${typeEnum.join('、')} 中的一种`)
      }
      return result
    }
  },
  // 描述文本
  content: {
    type: String,
    required: true
  },
  // 展示时长
  duration: {
    type: Number
  },
  // 关闭的回调
  destroy: {
    type: Function
  }
})
/**
 * 样式表数据结构
 */
const styles = {
  // 警告
  warn: {
    icon: 'warn',
    fillClass: 'fill-warn-300',
    textClass: 'text-warn-300',
    containerClass: 'bg-warn-100 border-warn-200 hover:shadow-lg hover:shadow-warn-100'
  },
  // 失败
  error: {
    icon: 'error',
    fillClass: 'fill-error-300',
    textClass: 'text-error-300',
    containerClass: 'bg-error-100 border-error-200 hover:shadow-lg hover:shadow-error-100'
  },
  // 成功
  success: {
    icon: 'success',
    fillClass: 'fill-success-300',
    textClass: 'text-success-300',
    containerClass: 'bg-success-100 border-success-200 hover:shadow-lg hover:shadow-success-100'
  }
}

// 控制展示
const isVisable = ref(false)
// 销毁延迟 0.5s 秒
const animDuration = '0.5s'
/**
 * 为了保证动画展示，需要在 onmounted 之后进行展示
 */
onMounted(() => {
  isVisable.value = true
  console.log(props.duration)
  setTimeout(() => {
    isVisable.value = false
    // setTimeout(() => {
    //   if (props.destroy) {
    //     props.destroy()
    //   }
    // }, parseInt(animDuration.replace('0.5', '').replace('s', '') * 100))
  }, props.duration)
})
</script>

<style scoped lang="scss">
.down-enter-active,
.down-leave-active {
  transition: all v-bind(animDuration);
}

.down-enter-from,
.down-leave-to {
  opacity: 0;
  transform: translate3d(-50%, -100px, 0);
}
</style>
